package dao

import (
	"context"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-sql-driver/mysql"
	"gorm.io/gorm"
	"time"
)

var (
	ErrDuplicateEmail = errors.New("邮箱冲突")
	ErrRecordNotFound = gorm.ErrRecordNotFound
)

type UserDao struct {
	db *gorm.DB
}

func NewUserDao(db *gorm.DB) *UserDao {
	return &UserDao{
		db: db,
	}
}

func (dao *UserDao) Insert(ctx context.Context, u User) error {
	now := time.Now().UnixMilli()
	u.Ctime = now
	u.Utime = now
	err := dao.db.WithContext(ctx).Create(&u).Error
	if me, ok := err.(*mysql.MySQLError); ok {
		const duplicateErr uint16 = 1062
		if me.Number == duplicateErr {
			// 用户冲突，邮箱冲突
			return ErrDuplicateEmail
		}
	}
	return err
}

func (dao *UserDao) FindByEmail(ctx context.Context, email string) (User, error) {
	var u User
	err := dao.db.WithContext(ctx).Where("email=?", email).First(&u).Error
	if err != nil {
		return User{}, ErrRecordNotFound
	}
	return u, nil
}

func (dao *UserDao) Update(ctx *gin.Context, user User) error {
	err := dao.db.WithContext(ctx).Where("id=?", user.Id).Updates(&user).Error
	if err != nil {
		return err
	}
	return nil
}

func (dao *UserDao) FindById(ctx context.Context, uid int64) (User, error) {
	var u User
	err := dao.db.WithContext(ctx).Where("id=?", uid).First(&u).Error
	if err != nil {
		return User{}, ErrRecordNotFound
	}
	return u, nil
}

type User struct {
	Id       int64  `gorm:"primaryKey,autoIncrement"`
	Email    string `gorm:"unique"`
	Password string

	// 时区， UTC 0 的毫秒数
	// 创建时间
	Ctime int64
	//更新时间
	Utime int64

	//json 存储
	Birthday string
	Nickname string
	AboutMe  string
}
type Address struct {
	Uid int64
}
